package com.zm.demo.core.nio;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/9/16 17:50
 */
public class PipeT {

    public static void main(String[] args) throws Exception{

        Pipe pipe = Pipe.open();

        write(pipe);
        read(pipe);


    }


    public static void write(Pipe pipe) throws Exception{
        Pipe.SinkChannel sinkChannel = pipe.sink();
        String newData = "New String to write to file...yyyy" + System.currentTimeMillis();
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());

        buf.flip();

        while(buf.hasRemaining()) {
            int rBytes = sinkChannel.write(buf);
            out.println(rBytes);
        }
    }

    public static void read(Pipe pipe) throws Exception{
        Pipe.SourceChannel sourceChannel = pipe.source();
        ByteBuffer buf = ByteBuffer.allocate(48);
        while(buf.hasRemaining()) {
            int rBytes = sourceChannel.read(buf);
            out.println(rBytes);
        }
    }
}
